package cn.com.wangluotongxin.service.service.impl;

import cn.com.wangluotongxin.admin.model.AdminPhoneCode;
import cn.com.wangluotongxin.admin.model.constants.YesNo;
import cn.com.wangluotongxin.service.mapper.AdminPhoneCodeMapper;
import cn.com.wangluotongxin.service.service.IAdminPhoneCodeService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * <p>
 * 网络通信-管理端-验证码发送记录 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2024-12-02
 */
@Service
public class AdminPhoneCodeServiceImpl extends ServiceImpl<AdminPhoneCodeMapper, AdminPhoneCode> implements IAdminPhoneCodeService {

    private final static String content = "【淘梦宝】验证码：%s，验证码10分钟内有效，为了保证你的账户安全，请勿向他人泄漏验证码!";

    @Override
    public AdminPhoneCode getByPhone(String phone, String code) {
        return this.getOne(new LambdaQueryWrapper<AdminPhoneCode>()
                .eq(AdminPhoneCode::getPhone, phone)
                .eq(AdminPhoneCode::getCode, code)
                .eq(AdminPhoneCode::getUseStatus, YesNo.NO.getCode())
                .gt(AdminPhoneCode::getExpireTime, DateUtil.offsetDay(DateUtil.date(), -1))
                .orderByDesc(AdminPhoneCode::getId)
                .last("limit 0,1"));
    }

    @Override
    public void sendPhoneCode(String phone) {
        String code = RandomUtil.randomNumbers(4);
        AdminPhoneCode phoneCode = new AdminPhoneCode();
        phoneCode.setPhone(phone);
        phoneCode.setCode(code);
        phoneCode.setUseStatus(YesNo.NO.getCode());
        phoneCode.setContent(String.format(content, code));
        phoneCode.setExpireTime(DateUtil.offsetMinute(DateUtil.date(), 10));
        this.save(phoneCode);
    }

    @Override
    public void authPhoneCode(String phone, String code) {
        AdminPhoneCode phoneCode = this.getByPhone(phone, code);
        Assert.notNull(phoneCode, "验证码输入错误");
        Assert.isTrue(phoneCode.getExpireTime().compareTo(DateUtil.date()) > 0, "验证码已失效");
        this.update(new LambdaUpdateWrapper<AdminPhoneCode>()
                .set(AdminPhoneCode::getUseStatus, YesNo.YES.getCode())
                .eq(AdminPhoneCode::getId, phoneCode.getId()));
    }
}
